package hu.mapro.rollerx.core;

import hu.mapro.rollerx.core.FractalTerrain.Vertices;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.operation.buffer.BufferParameters;

public class Ground4 extends AbstractGround {

	static final float AMPLITUDE = 20;
	static final float RADIUS = 30;
	static final float PLATFORM_MULTIPLIER = 2;
	static final float HEIGHT_MULTIPLIER = 3;
	
	public Ground4() {
		super(true, true);
	}
	
	void generateFractal(float carWidth) {
		fractalTerrain = new FractalTerrain();
		
		float halfPlatform = getPlatformWidth(carWidth)/2;
		
		fractalTerrain.x1 = (float) Math.atan(halfPlatform/RADIUS);
		fractalTerrain.x2 = (float) (Math.PI*2-fractalTerrain.x1);
		fractalTerrain.y1 = (float) Math.sqrt(RADIUS*RADIUS+halfPlatform*halfPlatform);
		fractalTerrain.y2 = fractalTerrain.y1;
		fractalTerrain.amplitude = 25;
		fractalTerrain.levels = 8;
		fractalTerrain.denominator = 2;
		
		vertices = new Vertices(fractalTerrain.getVertexCount());
		
		fractalTerrain.generateFractal(vertices);
	}

	static float getPlatformWidth(float carWidth) {
		return carWidth*PLATFORM_MULTIPLIER;
	}
	
	Vertices vertices;
	private FractalTerrain fractalTerrain;
	
	@Override
	Vector2[][] generateVertices(float carWidth, float carHeight) {
		generateFractal(carWidth);
		
		int coordCount = vertices.terrainVertices.length/2;
		Coordinate[] coords = new Coordinate[coordCount+1];
		for (int i=0;i<coordCount;i++) {
			coords[i] = new Coordinate(
					MathUtils.sin(vertices.terrainVertices[i*2])*vertices.terrainVertices[i*2+1], 
					MathUtils.cos(vertices.terrainVertices[i*2])*vertices.terrainVertices[i*2+1] 
			);
		}
		coords[coords.length-1]=coords[0];
		GeometryFactory geometryFactory = new GeometryFactory();
		LinearRing lineString = geometryFactory.createLinearRing(coords);
		
		BufferParameters bufferParameters = new BufferParameters();
		bufferParameters.setEndCapStyle(BufferParameters.CAP_ROUND);
		bufferParameters.setJoinStyle(BufferParameters.JOIN_BEVEL);
		Vector2[][] cave = Grounds.createCave(lineString, bufferParameters, getHeight(carHeight)/2);
		return cave;
	}

	@Override
	public Vector2 getCarPosition(float carWidth, float carHeight) {
		return new Vector2(0, RADIUS-getHeight(carHeight)/2);
	}

	float getHeight(float carHeight) {
		return carHeight*HEIGHT_MULTIPLIER;
	}
	
	
}
